
import "../../style/message.less";

interface Iparam {
  duration?: number;
  right?: 0;
  bottom?: 0;
  class?: string;
}
const Message = (content: string, params?: Iparam) => {
  let duration = params && params.duration ? params.duration : 1500;
  let right = params && params.right ? params.right : 0;
  let bottom = params && params.bottom ? params.bottom : 0;
  let classN = params && params.class ? params.class : "";
  // 销毁超出显示数量的消息 最多10条
  let arr = document.getElementsByClassName("ui-message-bg");
  if (arr.length === 10) {
    try {
      window.document.body.removeChild(arr[0]);
    } catch (error) {}
  }

  // 生成消息
  let obj = document.createElement("div");
  let achilddv = document.createElement("div");
  achilddv.innerHTML = `${content}`;
  achilddv.className = "ui-message-content";
  obj.className = "ui-message-bg";
  if (classN !== "") {
    obj.classList.add("ui-message-position");
    let dom = document.getElementsByClassName(classN)[0];
    let r = dom.getBoundingClientRect().left - right;
    let b = dom.getBoundingClientRect().top - dom.clientHeight - bottom;
    obj.style.cssText = `left:${r}px;top:${b}px`;
  }

  // 生成消息承载区
  let msgDom = document.getElementById("ui-message");
  if (!msgDom) {
    msgDom = document.createElement("div");
    msgDom.id = "ui-message";
    window.document.body.appendChild(msgDom);
  }
  msgDom.appendChild(obj);

  obj.appendChild(achilddv);
  if (duration === undefined || duration === null) duration = 1500;
  let maxTime = duration + 300;
  // 使用500毫秒产生动画
  setTimeout(() => {
    obj.style.cssText = "animation-name: message-hidden;";
  }, duration);
  // 销毁组件
  setTimeout(() => {
    try {
      msgDom?.removeChild(obj);
    } catch (error) {}
  }, maxTime);
};

export default Message;
